package com.qinggeng.project.api.utils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.APIConnectionException;
import cn.jpush.api.common.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Message.Builder;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.common.collect.Maps;
import com.qinggeng.common.enums.JpushUserEnum;
import com.qinggeng.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MessagePushUtils {
    private static PushPayload pushPayload;
    private static PushPayload.Builder builder =PushPayload.newBuilder();

    private static Boolean apnsProduction = false;

    public static void main(String[] args) throws Exception {
        //TODO(构建推送内容，推送目标，推送类型)
        //TODO（开始推送）
//
        HashMap<String, String> resultMap = Maps.newHashMap();
        resultMap.put("code", "001");//界面编码
        resultMap.put("arg", "212"); //参数
        resultMap.put("isReturn","1");//跳转类型（1=原生界面，0=不跳转，2=h5页面）
        pushPayload= push(Audience.alias("9ae480c57c264b356b4e31079b5c40f3"), "消息已推送", resultMap);

        sendPushTryCatch(JpushUserEnum.客户端, MessagePushUtils.pushPayload);
    }

    public enum JpushExtraEnum{
        Title,ContentType,DataType,Message
    }


    /**
     * @param @param payload
     * @Title: sendPushTryCatch TODO（开始推送）
     * @Description: try catch 推送
     */
    public static void sendPushTryCatch(JpushUserEnum userEnum,PushPayload payload) {
        JPushClient jPushClient = new JPushClient(userEnum.getMasterSecret(), userEnum.getAppKey());
        try {
            PushResult pushResult = jPushClient.sendPush(payload);
            log.info("返回结果" + pushResult);
        } catch (APIConnectionException e) {
            log.error("连接错误，稍后尝试" + e);
            throw new CustomException("连接错误，稍后尝试");
        } catch (APIRequestException e) {
            log.error("极光推送内部错误", e);
            log.info("网络请求状态" + e.getStatus());
            log.info("错误状态码" + e.getErrorCode());
            log.info("错误信息" + e.getErrorMessage());
            log.info("信息ID" + e.getMsgId());
            log.info("极光推送错误信息:" + e.getErrorMessage());
            //throw new CustomException("极光推送内部错误");
        }
    }

    /**
     * 推送
     *
     * @author kh.wang
     * @since 2016年3月24日
     * @param audience 推送方式
     * @param message 推送内容
     * @param extra 附加值
     */
    public static PushPayload push1(Audience audience,String message,Map<String, String> extra){
        Builder msgBuilder = Message.newBuilder().setMsgContent(message);

        IosNotification.Builder iosBuilder = IosNotification.newBuilder().setAlert(message);

        AndroidNotification.Builder androidBuilder = AndroidNotification.newBuilder().setAlert(message);

        if (extra != null && extra.size() > 0) {
            if (extra.containsKey(JpushExtraEnum.ContentType.name())) {
                msgBuilder.setContentType(extra.get(JpushExtraEnum.ContentType.name()));
                extra.remove(JpushExtraEnum.ContentType.name());
            }
            if (extra.containsKey(JpushExtraEnum.Title.name())) {
                msgBuilder.setTitle(extra.get(JpushExtraEnum.Title.name()));
                extra.remove(JpushExtraEnum.Title.name());
            }
            iosBuilder.addExtras(extra);
            msgBuilder.addExtras(extra);
            androidBuilder.addExtras(extra);
        }
        return builder
                .setPlatform(Platform.all())
                .setAudience(audience)
                .setNotification(Notification.newBuilder().setAlert(message).addPlatformNotification(iosBuilder.build()).build())
                .setNotification(Notification.newBuilder().setAlert(message).addPlatformNotification(androidBuilder.build()).build())
                .setOptions(Options.newBuilder().setApnsProduction(apnsProduction).build())
                .setMessage(msgBuilder.build())
                .build();

    }

    /**
     * @param audience   推送别名
     * @param message   推送标题
     * @param extra 推送内容（推荐json格式）
     * 给安卓 ios 都发推送
     * @return
     */
    public static PushPayload push(Audience audience,String message,Map<String, String> extra) {
        return builder
                .setPlatform(Platform.android_ios())  //推送平台
                .setAudience(audience)   //推送目标,这里指定进行别名推送
                .setNotification(Notification.newBuilder()
                        .setAlert(message)
                        .addPlatformNotification(
                                AndroidNotification.newBuilder()
                                        .addExtras(extra)
                                        .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtras(extra)
                                .build())
                        .build())
                .setOptions(
                        Options.newBuilder()
                                .setApnsProduction(false)//IOS推送環境、True 表示推送生产环境，False 表示要推送开发环境；
                                .setTimeToLive(0)   //推送当前用户不在线时，为该用户保留多长时间的离线消息，以便其上线时再次推送。默认 86400 （1 天），最长 10 天。设置为 0 表示不保留离线消息，只有推送当前在线的用户可以收到。
                                .build())
                .build();
    }

    /**
     * 角标推送
     *
     * @author kh.wang
     * @since 2016年5月3日
     * @param audience
     * @param badge
     */
    public static PushPayload pushBadge(Audience audience,int badge){
        return builder
                .setPlatform(Platform.all())
                .setAudience(audience)
                .setNotification(Notification.ios_set_badge(badge))
                .setOptions(Options.newBuilder().setApnsProduction(apnsProduction).build())//推送iPhone 通知
                .build();
    }

    /**
     * 自定义推送
     *
     * @author kh.wang
     * @since 2016年3月24日
     * @param audience 推送方式
     * @param message 推送内容
     * @param extra 附加值
     */
    public static PushPayload customPush(Audience audience,final String message,Map<String, String> extra){
        Builder msgBuilder = Message.newBuilder().setMsgContent(message);

        if (extra != null && extra.size() > 0) {
            if (extra.containsKey(JpushExtraEnum.ContentType.name())) {
                msgBuilder.setContentType(extra.get(JpushExtraEnum.ContentType.name()));
                extra.remove(JpushExtraEnum.ContentType.name());
            }
            if (extra.containsKey(JpushExtraEnum.Title.name())) {
                msgBuilder.setContentType(extra.get(JpushExtraEnum.Title.name()));
                extra.remove(JpushExtraEnum.Title.name());
            }
            msgBuilder.addExtras(extra);
        }
        return builder
                .setPlatform(Platform.all())
                .setAudience(audience)
                .setMessage(msgBuilder.build())
                .setOptions(Options.newBuilder().setApnsProduction(apnsProduction).build())//推送iPhone 通知
                .build();
    }

}
